package ch.jhc.db;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import ch.jhc.bean.User;

public class UserDao {
	
	//第一个操作 ，注册用户  ；   user自定义导入 create；
	public static void register(QueryRunner runner,User user) throws SQLException {
		//固定字符串前面加final
		final String sql = "insert into user(username, password, filename, sex, interests)" + "values(?,?,?,?,?)";
		
		//执行sql
		runner.execute(sql, user.getUsername(),user.getPassword(),user.getFilename(),user.getSex(),user.getInterests());
	}
	//第二个 ，用户登陆；
	public static User login(QueryRunner runner,String username,String password) throws SQLException{
		final String sql = "select id,username,password,filename,sex,interests from user where username=? and password=?";
		
		//执行runner,结果返回  
		return runner.query(sql, new BeanHandler<>(User.class),username,password);
	}
	
	//第三个，验证用户名是否被占用
	public static boolean exists(QueryRunner runner,String username) throws SQLException {
		final String sql = "select count(id) from user where username=?";
		//count 用 Long 返回
		Long result = runner.query(sql, new ScalarHandler<Long>(),username);
		//如果为1 则表示存在
		return result.longValue()==1L;
	}

}
